package prj.carmap.mobile.process;

import java.net.URLEncoder;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import prj.carmap.mobile.CarmapApplication;
import prj.carmap.mobile.R;
import prj.carmap.mobile.activity.FirstSplashActivity;
import prj.carmap.mobile.activity.LoginActivity;
import prj.carmap.mobile.activity.MainActivity;
import prj.carmap.mobile.activity.SellerSearchActivity;
import prj.carmap.mobile.model.UserInfo;
import prj.carmap.mobile.util.AccessLogUtil;
import prj.carmap.mobile.util.ViewUtil;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

/**
 * 登录请求处理
 * 
 */
public class LoginProcess extends AsyncHttpResponseHandler implements
		OnClickListener {

	private static AsyncHttpClient client = new AsyncHttpClient();

	private SharedPreferences mPreferences;
	private Context context;
	private Boolean isFirstIn;

	private EditText txtCardNo;
	private EditText txtPassword;
	private EditText txtPhone;
	private EditText txtModels;
	private EditText txtLicense;
	private Button btnLogin;

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnLogin:
//			 context.startActivity(new Intent(context,MainActivity.class));
			 context.startActivity(new Intent(context,
						MainActivity.class));
				((Activity) context).finish();
			 ((Activity)context).finish();
//			login();
			break;
		default:
			break;
		}
	}

	public void login() {
		// JSONObject jsonParams = new JSONObject();
		mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		String cardNo = txtCardNo.getText().toString().trim();
		String password = txtPassword.getText().toString().trim();
		String phoneNum = txtPhone.getText().toString().trim();
		String model = txtModels.getText().toString().trim();
		String license = txtLicense.getText().toString().trim();
		Editor edit = mPreferences.edit();

		edit.putString("cardNo", cardNo);
		edit.putString("password", password);
		edit.putString("phoneNum", phoneNum);
		edit.putString("txtModels", model);
		edit.putString("txtLicense", license);
		edit.commit();

		if (!isNetworkConnected()) {
			ViewUtil.makeToast(context, R.string.error_net_connect);
			return;
		} else if ("".equals(cardNo)) {
			ViewUtil.makeToast(context, R.string.error_empty_name);
			return;
		} else if ("".equals(password)) {
			ViewUtil.makeToast(context, R.string.error_empty_password);
			return;
		} else if (!phoneNum.matches("\\d{11}")) {
			ViewUtil.makeToast(context, R.string.error_phone_num);
			return;
		} else {
			btnLogin.setEnabled(false);
			try {
				Log.i("sss", model + "_" + license);
				client.get(
						CarmapApplication.SERVER_URL + "/rest/login/"
								+ URLEncoder.encode(cardNo, "utf-8") + "/"
								+ URLEncoder.encode(password, "utf-8") + "/"
								+ URLEncoder.encode(phoneNum, "utf-8") + "/"
								+ URLEncoder.encode(model, "utf-8") + "/"
								+ URLEncoder.encode(license, "utf-8"), this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public void login(String cardNo, String password, String phoneNum,
			String model, String license) {
		mPreferences = PreferenceManager.getDefaultSharedPreferences(context);
		if (!isNetworkConnected()) {
			ViewUtil.makeToast(context, R.string.error_net_connect);
			context.startActivity(new Intent(context, LoginActivity.class));
			return;
		} else if ("".equals(cardNo)) {
			ViewUtil.makeToast(context, R.string.error_empty_name);
			context.startActivity(new Intent(context, LoginActivity.class));
			return;
		} else if ("".equals(password)) {
			ViewUtil.makeToast(context, R.string.error_empty_password);
			context.startActivity(new Intent(context, LoginActivity.class));
			return;
		} else if (!phoneNum.matches("\\d{11}")) {
			ViewUtil.makeToast(context, R.string.error_phone_num);
			context.startActivity(new Intent(context, LoginActivity.class));
			return;
		} else {
			// btnLogin.setEnabled(false);
			try {
				client.get(
						CarmapApplication.SERVER_URL + "/rest/login/"
								+ URLEncoder.encode(cardNo, "utf-8") + "/"
								+ URLEncoder.encode(password, "utf-8") + "/"
								+ URLEncoder.encode(phoneNum, "utf-8") + "/"
								+ URLEncoder.encode(model, "utf-8") + "/"
								+ URLEncoder.encode(license, "utf-8"), this);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	/**
	 * Fired when a request returns successfully, override to handle in your own
	 * code
	 * 
	 * @param content
	 *            the body of the HTTP response from the server
	 * @throws JSONException
	 */
	public void onSuccess(String content) {
		try {
			JSONObject json = new JSONObject(content);
			Log.i("sss", content);
			if (json.getString("cardNo") != "null") {
				// 登录成功
				UserInfo userInfo = new UserInfo();
				userInfo.cardNo = json.getString("cardNo");
				userInfo.phone = json.getString("telephone");
				userInfo.name = json.getString("name");
				userInfo.models = json.getString("carType");
				userInfo.license = json.getString("carNo");
				CarmapApplication.getInstance().isLogin = true;
				CarmapApplication.getInstance().userInfo = userInfo;
				isFirstIn = mPreferences.getBoolean("isFirstIn", true);
				if (!isFirstIn) {
					context.startActivity(new Intent(context,
							MainActivity.class));
					((Activity) context).finish();
				} else {
					Intent intent = new Intent(context,
							FirstSplashActivity.class);
					context.startActivity(intent);
					((Activity) context).finish();
				}
				// 发送登录log给服务器
				StringEntity log = AccessLogUtil.createAccessLogTypeParam(1);
				if (log != null)
					new AsyncHttpClient().post(context,
							CarmapApplication.SERVER_URL + "/rest/accesslog",
							log, "application/json",
							new AsyncHttpResponseHandler());
			} else {
				ViewUtil.makeToast(context, R.string.error_login);
				if (btnLogin != null) {
					btnLogin.setEnabled(true);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Fired when a request fails to complete, override to handle in your own
	 * code
	 * 
	 * @param error
	 *            the underlying cause of the failure
	 * @param content
	 *            the response body, if any
	 */
	public void onFailure(Throwable error, String content) {
		ViewUtil.makeToast(context, "登录异常！" + error.getMessage());
		// btnLogin.setEnabled(true);
		context.startActivity(new Intent(context, LoginActivity.class));
	}

	public boolean isNetworkConnected() {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		if (manager == null) {
			return false;
		}

		NetworkInfo[] infos = manager.getAllNetworkInfo();
		for (NetworkInfo info : infos) {
			if (info.isConnected()) {
				return true;
			}
		}

		return false;
	}

	public EditText getTxtCardNo() {
		return txtCardNo;
	}

	public void setTxtCardNo(EditText txtCardNo) {
		this.txtCardNo = txtCardNo;
	}

	public EditText getTxtPassword() {
		return txtPassword;
	}

	public void setTxtPassword(EditText txtPassword) {
		this.txtPassword = txtPassword;
	}

	public EditText getTxtPhone() {
		return txtPhone;
	}

	public void setTxtPhone(EditText txtPhone) {
		this.txtPhone = txtPhone;
	}

	public Button getBtnLogin() {
		return btnLogin;
	}

	public void setBtnLogin(Button btnLogin) {
		this.btnLogin = btnLogin;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public EditText getTxtModels() {
		return txtModels;
	}

	public void setTxtModels(EditText txtModels) {
		this.txtModels = txtModels;
	}

	public EditText getTxtLicense() {
		return txtLicense;
	}

	public void setTxtLicense(EditText txtLicense) {
		this.txtLicense = txtLicense;
	}

}
